
<form action="" method="post" class="form-horizontal ajax-submit">

	<div class="form-group">
		<label class="col-sm-1 control-label">轮播图</label>
		<div class="col-sm-6">
    		<div style="display: none">
                <button id="_pickfiles" class="btn btn-default">选择文件</button>
                <button id="_uploadBtn" class="btn btn-info">上传</button>
            </div>
            <div id="fsUploadProgress">
			<?php if (!empty($info['pic'])):?>
    			<div class="up-item">
    			    <button class="close"><span>&times;</span></button>
    			    <img src="<?= $info['pic']?>" width="160" class="img-thumbnail">
		            <input type="hidden" class="form-control" name="pic[]" value="<?= $info['pic']?>" >
    			</div>
			<?php endif;?>
			</div>
			<div id="pickfiles" style="display: inline-block; <?php if (!empty($info['pic'])):?>display:none<?php endif;?>" >
			    <img class="img-thumbnail" src="<?= URL::site('static/img/default.png')?>">
		    </div>
		</div>
	</div>
	
	<div class="form-group">
		<label class="col-sm-1 control-label">所在位置</label>
		<div class="col-sm-3">
			<select class="form-control" name="category" required>
				<option value="">-选择轮播图位置-</option>
                <option value="1" <?php if(Arr::get($_GET, 'category')=='1'):?>selected<?php endif;?>>PC首页轮播图</option>
                <option value="2" <?php if(Arr::get($_GET, 'category')=='2'):?>selected<?php endif;?>>PC行业资讯轮播图</option>
                <option value="3" <?php if(Arr::get($_GET, 'category')=='3'):?>selected<?php endif;?>>APP端首页轮播</option>
                <option value="4" <?php if(Arr::get($_GET, 'category')=='4'):?>selected<?php endif;?>>APP端课堂轮播</option>
                <option value="5" <?php if(Arr::get($_GET, 'category')=='5'):?>selected<?php endif;?>>APP端课堂精品轮播</option>
			</select>
		</div>
	</div>
	
	<div class="form-group">
		<label class="col-sm-1 control-label">图片注释</label>
		<div class="col-sm-3">
			<input type="number" id="desc" name="desc" value="<?= $info['desc']?>" required/>
			<p style="color: red">请注释轮播图第一张,标记为1.其余任意</p>
		</div>
	</div>
	
	<div class="form-group">
		<label class="col-sm-1 control-label">跳转地址</label>
		<div class="col-sm-11">
			<input style="width:500px;" type="text" id="jump_url" name="jump_url" value="<?= $info['jump_url']?>" required />
		</div>
	</div>
	
	<div class="form-group">
		<div class="col-sm-offset-1 col-sm-3">
			<button type="submit" class="btn btn-primary">提交</button>
		</div>
	</div>
</form>

<style>
div.mce-fullscreen {z-index: 9999;}
.mce-menubtn.mce-fixed-width span {width:auto}
</style>
<?= HTML::script('static/tinymce/tinymce.min.js')?>
<script type="text/javascript">
tinyMCE.init({
	selector : 'textarea#editor',
	plugins: [
		  		"advlist autolink lists link image charmap print preview anchor",
		  		"searchreplace visualblocks code fullscreen imagetools upload",
		  		"insertdatetime media table contextmenu paste textcolor colorpicker emoticons",
		  		"codesample eqneditor"
		  	],
  	toolbar: "upload undo redo | fontselect fontsizeselect forecolor | bold italic | link image emoticons | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | fullscreen preview",
  	autosave_ask_before_unload: false,
  	convert_urls: false,
    force_br_newlines : true,
    force_p_newlines : false,
    forced_root_block : '', // Needed for 3.x
	height : 400,
	content_css: ['<?= URL::site('static/css/preview.css')?>'],
	language: 'zh_CN'
});
</script>


<style>
.up-item{float:left;width:160px;margin:5px;position:relative}
.up-item .close{position:absolute;right:3px;top:0;}
.up-item .img-thumbnail{width:160px;}
.up-item .progress{position:absolute;left:0;bottom:0;width:100%;height:8px;margin:0;display:none}
</style>
<?php include __DIR__ . '/../plupload.php';?>

<script>
accessid = ''
accesskey = ''
host = ''
policyBase64 = ''
signature = ''
callbackbody = ''
filename = ''
key = ''
expire = 0
g_object_name = ''
g_object_name_type = ''
now = timestamp = Date.parse(new Date()) / 1000; 

function send_request()
{
    var xmlhttp = null;
    if (window.XMLHttpRequest)
    {
        xmlhttp=new XMLHttpRequest();
    }
    else if (window.ActiveXObject)
    {
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
  
    if (xmlhttp!=null)
    {
        serverUrl = '<?= URL::site('aliyunoss/uptoken?type=article')?>'
        xmlhttp.open( "GET", serverUrl, false );
        xmlhttp.send( null );
        return xmlhttp.responseText
    }
    else
    {
        alert("Your browser does not support XMLHTTP.");
    }
};

function check_object_radio() {
    var tt = document.getElementsByName('myradio');
    for (var i = 0; i < tt.length ; i++ )
    {
        if(tt[i].checked)
        {
            g_object_name_type = tt[i].value;
            break;
        }
    }
}

function get_signature()
{
    //可以判断当前expire是否超过了当前时间,如果超过了当前时间,就重新取一下.3s 做为缓冲
    now = timestamp = Date.parse(new Date()) / 1000; 
    if (expire < now + 3)
    {
        body = send_request()
        var obj = eval ("(" + body + ")");
        host = obj['host']
        policyBase64 = obj['policy']
        accessid = obj['accessid']
        signature = obj['signature']
        expire = parseInt(obj['expire'])
        callbackbody = obj['callback'] 
        key = obj['dir']
        return true;
    }
    return false;
};

function random_string(len) {
　　len = len || 32;
　　var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';   
　　var maxPos = chars.length;
　　var pwd = '';
　　for (i = 0; i < len; i++) {
    　　pwd += chars.charAt(Math.floor(Math.random() * maxPos));
    }
    return pwd;
}

function get_suffix(filename) {
    pos = filename.lastIndexOf('.')
    suffix = ''
    if (pos != -1) {
        suffix = filename.substring(pos)
    }
    return suffix;
}

function calculate_object_name(filename)
{
    /*if (g_object_name_type == 'local_name')
    {
        g_object_name += "${filename}"
    }
    else if (g_object_name_type == 'random_name')
    {*/
        suffix = get_suffix(filename)
        g_object_name = key + random_string(10) + suffix
    //}
    return ''
}

function get_uploaded_object_name(filename)
{
    /*if (g_object_name_type == 'local_name')
    {
        tmp_name = g_object_name
        tmp_name = tmp_name.replace("${filename}", filename);
        return tmp_name
    }
    else if(g_object_name_type == 'random_name')
    {*/
        return g_object_name
    //}
}

function set_upload_param(up, filename, ret)
{
    if (ret == false)
    {
        ret = get_signature()
    }
    g_object_name = key;
    if (filename != '') {
        suffix = get_suffix(filename)
        calculate_object_name(filename)
    }
    new_multipart_params = {
        'key' : g_object_name,
        'policy': policyBase64,
        'OSSAccessKeyId': accessid, 
        'success_action_status' : '200', //让服务端返回200,不然，默认会返回204
        'callback' : callbackbody,
        'signature': signature,
    };

    up.setOption({
        'url': host,
        'multipart_params': new_multipart_params
    });

    up.start();
}

$(function() {
	var uploader = new plupload.Uploader({
		browse_button : 'pickfiles',
		multi_selection: false,
		url : 'http://oss.aliyuncs.com',
		flash_swf_url : '<?= URL::site('static/plupload/Moxie.swf')?>',
		silverlight_xap_url : '<?= URL::site('static/plupload/Moxie.xap')?>',
		filters: {
			mime_types: [{
				title : "图片文件", 
				extensions: "jpg,gif,png"
			}],
            max_file_size : '10000kb',
			prevent_duplicates : true
	    }
	});
	uploader.init();

	uploader.bind('FilesAdded',function(up,files){
		console.log(up, files);
        plupload.each(files, function(file) {
        	var progress = new FileProgress(file, 'fsUploadProgress');
        	$('#pickfiles').hide();
        	$('input[type=file]').parent('div').hide();

    		var remove_btn = $('#'+file.id).find('.close');
    		remove_btn.click(function(){
    			uploader.removeFile(file);
    			$('#pickfiles').show();
            	$('input[type=file]').parent('div').show();
    		});
        });
        set_upload_param(uploader, '', false);
        //this.start();
	});
	uploader.bind('BeforeUpload',function(up, file){
		$('#'+file.id).find('.progress').show();
		
		set_upload_param(up, file.name, true);
        this.start();
	});
	uploader.bind('UploadProgress',function(up, file){
        var progress = new FileProgress(file, 'fsUploadProgress');
	    progress.setProgress(file.percent);
	});
	uploader.bind('FileUploaded',function(up, file, info){
        var progress = new FileProgress(file, 'fsUploadProgress');
        progress.setComplete(up, file, info);

        if (info.status == 200) {
        	var url = 'http://jtkj.oss-cn-beijing.aliyuncs.com/' + get_uploaded_object_name();
        //}

    	//var res = info.response;
    	//res = eval('('+res+')');
    	//if (res.status=='ok') {
    	//    var url = '/imagefly/w200/'+res.data;
    	    $('#'+file.id).find('img').attr('src', url + '?x-oss-process=image/resize,m_fill,h_120,w_160');
    	    $('#'+file.id).find('input').val(url);


    	    var image = new Image();
            image.src = url;
            image.onload = function() {
                var w = image.width;
                var h = image.height;
            
                $.get('/upload/add',{'img_url':url, 'file_size': file.size, 'img_width': w, 'img_height': h},function(){});
            }
    	}
	});

	$(document).on('click', '.up-item .close', function(){
		$(this).parents('.up-item').remove();
		$('#pickfiles').show();
    	$('input[type=file]').parent('div').show();
	});

    $('#uploadBtn').click(function() {
    	uploader.start();
    	return false;
    });
});
</script>

